#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import subprocess
import tarfile
import shutil
import yaml
import argparse
from collections import defaultdict

import sys
reload(sys)
sys.setdefaultencoding('utf8')


def tar(filelist, path_name):
    tf = tarfile.open(path_name, "w:gz")

    for file_name in filelist:
        tf.add(file_name)

    tf.close()

def get_config(file_name):
    """
    解析yaml
    :file_name: 配置文件名
    :returns: setting dict

    """

    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        ins = None
        try:
            ins = yaml.load(f, Loader=yaml.FullLoader) #高版本
        except Exception as e:
            ins = yaml.load(f)
        return ins

def send_mail(mail, title, send_str, files, del_file=True):
    """
    发送邮件， mail为通过 get_config 拿到的 mail 的配置
    详见配置文件 oss.yaml
    """
    sender = mail.get('sender', '')
    receiver = mail.get('receiver', [])
    server = mail.get('SMTP_server', '')
    port = mail.get('SMTP_port', 465)
    password = mail.get('password', '')

    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')
    msg['From'] = 'server<%s>' %sender
    msg['To'] = ';'.join(receiver)
    msg.attach(MIMEText(send_str, 'plain', 'utf-8'))

    #add attachment
    for path in files:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)
        del_file and os.remove(path)

    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(server)
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.login(sender, password)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(receiver))
        print(e)
    smtp.quit()

def argument_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--mail', help='wether to send mail or not',  action='store_true')
    parser.add_argument('-s', '--subject', help='the subject of mail',  default='taptap')

    parser.add_argument('-f', '--file', help='the path about statistics file',  default='statistics.txt')

    parser.add_argument('-H', '--host', help='mysql host',  default='localhost')
    parser.add_argument('-P', '--PORT', help='mysql port',  default='3306')
    parser.add_argument('-u', '--user', help='mysql user\'s name',  default='root')
    parser.add_argument('-p', '--password', help='mysql user\'s passwrod', required=True)
    parser.add_argument('-D', '--database', help='database name',  default='oss')
    parser.add_argument('-c', '--character', help='the setting about mysql database\'s character', default='utf8')
    parser.add_argument('-C', '--choice', help='the setting about mysql database\'s character', type=int, choices=[0,1,2])

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-d', '--days', help='collect the statistics information from which day to yesterday', type=int)
    group.add_argument('-t', '--timestamp', help='collect the statistics information about the day of the timestamp', type=int)
    group.add_argument('-y', '--yesterday', help='collect the yesterday\'s statistics information', action='store_true')

    return parser.parse_args()

